package com.dmg.sp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.dmg.sp.dao.UserMapper;
import com.dmg.sp.entity.Role;
import com.dmg.sp.entity.User;
import com.dmg.sp.service.SysUserService;
import com.dmg.sp.vo.UserRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private UserMapper userMapper;


    /**
     * 获取所有用户
     * @return
     */
    @Override
    public List<User> getUserList() {
        return userMapper.selectList(null);
    }

    /**
     * 为用户分配角色
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void setUserRole(UserRoleVo vo) {
        //判断用户是否存在
        if(vo.getUserId()==null || userMapper.selectById(vo.getUserId())==null){
            throw new RuntimeException("用户不存在");
        }
        if(CollectionUtils.isEmpty(vo.getRoleIds())){
            throw new RuntimeException("角色不能为空");
        }
        //先删除旧的用户角色
        userMapper.deleteRole(vo.getUserId());
        //在添加新的用户角色
        userMapper.addUserRole(vo.getUserId(),vo.getRoleIds());
    }


    /**
     * 添加用户
     * @param user
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(User user) {
        //根据账号获取用户信息
        if(getByAccount(user.getAccount())!=null){
            throw new RuntimeException("该账号已存在");
        }
        //对密码进行加密
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }


    /**
     * 查看用户对应的角色id
     * @return
     */
    @Override
    public List<Integer> getUserRoleIds(Integer userId) {
        return userMapper.getUserRoleIds(userId);
    }

    /**
     * 根据账号获取用户信息
     * @param account
     * @return
     */
    private User getByAccount(String account){
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.eq("account",account);
        User x=userMapper.selectOne(queryWrapper);
        return x;
    }
}
